package com.example.studyproject.thread;

import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: StudyProject
 * @description: 线程池封装
 * @author: kangwei
 * @create: 2025-07-03 16:08
 **/

@Component
public class ThreadPoolExecutorWrapper {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    ;

    /**
     * 线程池执行
     *
     * @param poolExecutor
     * @param runExecute
     */
    public void execute(ThreadPoolExecutor poolExecutor, CallExecute runExecute) {
        if (null != poolExecutor) {
            poolExecutor.execute(runExecute::call);
        } else {
            threadPoolExecutor.execute(runExecute::call);
        }
    }

    /**
     * submit 提交
     *
     * @param poolExecutor
     * @param runExecute
     * @return
     */
    public Future submit(ThreadPoolExecutor poolExecutor, CallExecute runExecute) {
        if (null != poolExecutor) {
            Future<?> submit = poolExecutor.submit(runExecute::call);
            return submit;
        } else {
            return threadPoolExecutor.submit(runExecute::call);
        }
    }

    /**
     * 无需返回Future
     *
     * @param poolExecutor
     * @param runExecute
     */
    public void submitNoReturn(ThreadPoolExecutor poolExecutor, CallExecute runExecute) {
        if (null != poolExecutor) {
            poolExecutor.submit(runExecute::call);
        } else {
            threadPoolExecutor.submit(runExecute::call);
        }
    }

    /**
     * ExecutorService
     *
     * @param executorService
     * @param runExecute
     * @return
     */
    public Future submit(ExecutorService executorService, CallExecute runExecute) {
        if (null != executorService) {
            Future<?> submit = executorService.submit(runExecute::call);
            return submit;
        } else {
            return threadPoolExecutor.submit(runExecute::call);
        }
    }


}
